package com.steven.door.activity;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.widget.NestedScrollView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.example.x6.serial.SerialUtil;
import com.steven.door.R;
import com.steven.door.base.BaseActivity;
import com.steven.door.base.SelectListener;
import com.steven.door.base.SerialCode;
import com.steven.door.base.WEBCode;
import com.steven.door.entity.ResultEntity;
import com.steven.door.manager.ThreadPoolManager;
import com.steven.door.net.MyCallback;
import com.steven.door.net.TaskNoHead;
import com.steven.door.services.WebSocketService;
import com.steven.door.utils.ByteUtils;
import com.steven.door.utils.CenterDialog;
import com.steven.door.utils.DataCheckUtils;
import com.steven.door.utils.SPUtils;
import com.steven.door.utils.SystemUtils;
import com.steven.door.utils.TimeUtil;
import com.steven.door.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Response;


public class MainActivity extends BaseActivity implements WEBCode, SerialCode {

    //    @BindView(R.id.tv_0)
//    TextView tv0;
//    @BindView(R.id.tv_1)
//    TextView tv1;
//    @BindView(R.id.tv_2)
//    TextView tv2;
//    @BindView(R.id.tv_3)
//    TextView tv3;
//    @BindView(R.id.tv_4)
//    TextView tv4;
//    @BindView(R.id.tv_5)
//    TextView tv5;
//    @BindView(R.id.tv_6)
//    TextView tv6;
//    @BindView(R.id.tv_7)
//    TextView tv7;
//    @BindView(R.id.tv_8)
//    TextView tv8;
//    @BindView(R.id.tv_9)
//    TextView tv9;
//    @BindView(R.id.tv_delete)
//    TextView tvDelete;
//    @BindView(R.id.tv_back)
//    TextView tvBack;
    @BindView(R.id.tv_pickCode)
    TextView tv_pickCode;


    @BindView(R.id.edit_name)
    EditText editName;
    @BindView(R.id.edit_send_phone)
    EditText editSendPhone;
    @BindView(R.id.edit_address)
    EditText editAddress;
    @BindView(R.id.edit_num)
    EditText editNum;

    @BindView(R.id.edit_uniCode)
    EditText editUniCode;

    @BindView(R.id.tv_specification)
    TextView tvSpecification;

    @BindView(R.id.ll_click)
    LinearLayout llClick;
    @BindView(R.id.ll_normal)
    LinearLayout llNormal;

    @BindView(R.id.ll_click2)
    NestedScrollView llClick2;

    @BindView(R.id.tv_time)
    TextView tv_time;

    @BindView(R.id.rel_load)
    RelativeLayout rel_l;

    private String pickCode;//目前取件码限制六位数字
    private StringBuilder sb = new StringBuilder();
    private boolean isScan = true;
    private int select = 1;//3 大 2 中 1 小
    private TimeReceive timeReceive;

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String str) {
        //获取出价记录  然后进行设置
        try {
            switch (str) {
                case "open": //开启状态
                    ToastUtils.showToast(this,"锁已经打开！");
                    break;
                case "close": //关闭状态
                    ToastUtils.showToast(this,"锁已经关闭！");
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




    @OnClick({R.id.tv_0, R.id.tv_1, R.id.tv_2, R.id.tv_3, R.id.tv_4, R.id.tv_5, R.id.tv_6, R.id.tv_7, R.id.tv_8, R.id.tv_9, R.id.tv_delete, R.id.tv_back
            , R.id.ll_pick, R.id.ll_mail, R.id.tv_commit, R.id.back, R.id.tv_specification, R.id.rel_load
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rel_load://进度条
                break;
            case R.id.tv_0://0
                sb.append("0");
                tv_pickCode.setText(sb.toString());
                break;
            case R.id.tv_1://1
                sb.append("1");
                tv_pickCode.setText(sb.toString());
                break;
            case R.id.tv_2://2
                sb.append("2");
                tv_pickCode.setText(sb.toString());
                break;
            case R.id.tv_3://3
                sb.append("3");
                tv_pickCode.setText(sb.toString());
                break;
            case R.id.tv_4://4
                sb.append("4");
                tv_pickCode.setText(sb.toString());
                break;
            case R.id.tv_5://5
                sb.append("5");
                tv_pickCode.setText(sb.toString());
                break;
            case R.id.tv_6://6
                sb.append("6");
                tv_pickCode.setText(sb.toString());
                break;
            case R.id.tv_7://7
                sb.append("7");
                tv_pickCode.setText(sb.toString());
                break;
            case R.id.tv_8://8
                sb.append("8");
                tv_pickCode.setText(sb.toString());
                break;
            case R.id.tv_9://9
                sb.append("9");
                tv_pickCode.setText(sb.toString());
                break;
            case R.id.tv_delete://刪除
                if (sb.length() != 0) {
                    sb.delete(sb.length() - 1, sb.length());
                }
                tv_pickCode.setText(sb.toString());
                break;
            case R.id.tv_back://返回
                llClick.setVisibility(View.GONE);
                llNormal.setVisibility(View.VISIBLE);
                break;
            case R.id.ll_pick://取件
                llClick.setVisibility(View.VISIBLE);
                llNormal.setVisibility(View.GONE);
                llClick2.setVisibility(View.GONE);
                break;
            case R.id.ll_mail://寄件
                initSendData();
                llClick.setVisibility(View.GONE);
                llNormal.setVisibility(View.GONE);
                llClick2.setVisibility(View.VISIBLE);
                llClick2.fling(0);
                llClick2.smoothScrollTo(0, 0);
                break;
            case R.id.tv_commit:
                commit();
                break;
            case R.id.back://返回
                llClick2.setVisibility(View.GONE);
                llNormal.setVisibility(View.VISIBLE);
                break;
            case R.id.tv_specification://弹出选择框
                new CenterDialog(R.layout.dialog, this).showSelect(new SelectListener() {
                    @Override
                    public void select(int position) {
                        select = position;//表示选中之后
                        switch (select) {
                            case 3:
                                tvSpecification.setText("柜子规格：大");
                                break;
                            case 2:
                                tvSpecification.setText("柜子规格：中");
                                break;
                            case 1:
                                tvSpecification.setText("柜子规格：小(默认)");
                                break;
                        }
                    }
                }, select);
                break;
        }
    }


    //初始化寄件信息
    private void initSendData() {
        editSendPhone.setText("");
        editAddress.setText("");
        editName.setText("");
        editNum.setText("");
        editUniCode.setText("");
        tvSpecification.setText("请点击选择柜子规格：小(默认)");
        select = 1;
    }

    //提交信息
    private void commit() {
        rel_l.setVisibility(View.VISIBLE);
        String sendPhone = editSendPhone.getText().toString();
        String address = editAddress.getText().toString();
        String name = editName.getText().toString();
        String num = editNum.getText().toString();
        String uniCode = editUniCode.getText().toString();
        String mac = SPUtils.get(this, "mac", "") + "";
        if (!sendPhone.equals("") && !address.equals("") && !name.equals("") && !num.equals("") && !uniCode.equals("")) {
            if (!DataCheckUtils.isCellphone(sendPhone)) {
                rel_l.setVisibility(View.GONE);
                ToastUtils.showToast(this, "请输入正确的手机号~");
                return;
            }

            //开始进行提交数据
            TaskNoHead.getInstance().send("uid123456", mac, select, sendPhone, name, address, uniCode, num).enqueue(new MyCallback<ResultEntity>() {
                @Override
                protected void onSuccess(Response response) {
                    try {
                        rel_l.setVisibility(View.GONE);
                        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(response.body());
                        assert jsonObject != null;
                        if (jsonObject.getInteger("code") == 0) {
                            String order_id = jsonObject.getJSONObject("data").getString("order_id");//生成订单号

                            String cases = jsonObject.getJSONObject("data").getString("cases");//柜号

                            String doors = jsonObject.getJSONObject("data").getString("doors");//门号

                            String mac_id = jsonObject.getJSONObject("data").getString("mac_id");//设备的 mac地址

                            int take_code = jsonObject.getJSONObject("data").getInteger("take_code");//取件码
                            SPUtils.put(MainActivity.this, "order_id", order_id);
                            llClick2.setVisibility(View.GONE);
                            llNormal.setVisibility(View.VISIBLE);
                        } else {
                            ToastUtils.showToast(MainActivity.this, jsonObject.getString("msg"));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        rel_l.setVisibility(View.GONE);
                    }
                }

                @Override
                protected void onFailure(Throwable t) {
                    rel_l.setVisibility(View.GONE);
                }
            });

        } else {
            rel_l.setVisibility(View.GONE);
            ToastUtils.showToast(this, "请完善以上信息~");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (timeReceive != null) {
            unregisterReceiver(timeReceive);
        }
    }


    @Override
    public int intiLayout() {
        return R.layout.activity_main;
    }

    @Override
    public void intiView() {
        EventBus.getDefault().register(this);
        tv_time.setText(TimeUtil.getTime());
        tvSpecification.setText("请点击选择柜子规格：小(默认)");
        timeReceive = new TimeReceive();
        IntentFilter s_intentFilter;
        s_intentFilter = new IntentFilter();
        s_intentFilter.addAction(Intent.ACTION_TIME_TICK);
        s_intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
        s_intentFilter.addAction(Intent.ACTION_TIME_CHANGED);
        registerReceiver(timeReceive, s_intentFilter);
    }

    @Override
    public void intiData() {
        tv_pickCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                pickCode = tv_pickCode.getText().toString();
                if (pickCode.length() == 6) {
                    pickApply(pickCode);
//                    if (pickCode.equals("123456")) {
//                        //开门
////                        byte[] open = ByteUtils.concatAll(doorHead, openDoor, open_door, doorEnd);
////                        SerialUtil.getInstance().openDoor(open);
////                        byte[] watch = ByteUtils.concatAll(doorHead, openDoor, query, doorEnd);
////                        SerialUtil.getInstance().watchSerial(watch);
//                        sb.delete(0, sb.length());
//                        tv_pickCode.setText(sb.toString());
//                    } else {
//                        sb.delete(0, sb.length());
//                        tv_pickCode.setText(sb.toString());
//                        ToastUtils.showToast(MainActivity.this, "取件码不正确！");
//                    }
                }
            }
        });
    }
  //取件请求
    private void pickApply(String pickCode){
        rel_l.setVisibility(View.VISIBLE);
        String mac=SPUtils.get(this,"mac","")+"";
        TaskNoHead.getInstance().receive(mac,pickCode).enqueue(new MyCallback<ResultEntity>() {
            @Override
            protected void onSuccess(Response response) {
                try {
                    sb.delete(0, sb.length());
                    tv_pickCode.setText(sb.toString());
                    JSONObject jsonObject = (JSONObject) JSONObject.toJSON(response.body());
                    assert jsonObject != null;
                    if (jsonObject.getInteger("code") == 0) {
                        rel_l.setVisibility(View.GONE);
                    } else {
                        rel_l.setVisibility(View.GONE);
                        ToastUtils.showToast(MainActivity.this, jsonObject.getString("msg"));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    rel_l.setVisibility(View.GONE);
                }
            }

            @Override
            protected void onFailure(Throwable t) {
                rel_l.setVisibility(View.GONE);
            }
        });
    }
    private class TimeReceive extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            assert action != null;
            if (action.equals(Intent.ACTION_TIME_TICK)) {
                tv_time.setText(TimeUtil.getTime());
            }
        }
    }
}
